<template>
	<div class="zBox">
		<div class="title">
			<span v-if="!isInDocument">{{ projectName }}</span>
			<span v-else>{{ projectName + '—' + zlName }}</span>
			<div v-if="!isInDocument" class="qjBut" @click="addFolders"><span style="vertical-align: middle;margin-left: 8px;">创建资料夹</span></div>
			<div v-else class=" hbj" @click="comeBack"><span style="vertical-align: middle;margin-left: 8px;">返回资料夹</span></div>
		</div>
		<div v-if="!isInDocument" class="">
			<el-table class="qjTable" v-loading="loading" :data="tableList" stripe height="600">
				<el-table-column label="文件" align="center">
					<template #default="scope">
						<div style="display: flex;align-items: center;justify-content: flex-start;margin-left: 100px;" id="">
							<img width="30" height="30" src="../../assets/images/mainImg/wenJian.png" alt class="fileicon" />
							<span style="margin-left: 20px;">{{ scope.row.title }}</span>
						</div>
					</template>
				</el-table-column>
				<el-table-column prop="createTime" label="创建日期" align="center"></el-table-column>
				<el-table-column prop="fileNum" label="文件数量(件)" align="center"></el-table-column>
				<el-table-column label="操 作" width="300" align="center" class-name="small-padding">
					<template #default="scope">
						<div class="czan">
							<div v-if="userId == scope.row.principalId" class="czBut xj" @click="showUpload(scope.row)">上传文件</div>
							<div class="czBut bjckdj" @click="seeWjk(scope.row)">查看</div>
							<div v-if="scope.row.createBy == userName" class="czBut scbj" @click="deleteWjk(scope.row)">删除</div>
						</div>
					</template>
				</el-table-column>
			</el-table>
			<pagination class="pagination" v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
		</div>
		<div v-else class="">
			<el-table class="qjTable"   :data="tableList" stripe height="600">
				<el-table-column label="文件" align="center">
					<template #default="scope">
						<span style="">{{ scope.row.documentName }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="createTime" label="文件大小" align="center">
					<template #default="scope">
						<span style="color: #000000;">{{ (scope.row.documentSize / 1024 / 1024).toFixed(3) + 'M' }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="createTime" label="上传时间" align="center"></el-table-column>
				<el-table-column label="操 作" width="300" align="center" class-name="small-padding">
					<template #default="scope">
						<div class="czan">
							<div class="czBut xj" @click="downloadFile(scope.row)">下载</div>
							<div v-if="scope.row.createBy == userName" class="czBut scbj" @click="deleteWjk(scope.row)">删除</div>
						</div>
					</template>
				</el-table-column>
			</el-table>
		</div>

		<el-dialog class="addDialog"  :close-on-press-escape="false" v-model="addDialog" title="创建资料夹" top="30vh" width="20.5%" :close-on-click-modal="false">
			<el-form ref="ruleFormRef" :model="addForm" :rules="rules" label-width="120px" label-position="top">
				<el-form-item style=" width: 100%;" label="资料夹名称" prop="title"><el-input style="height: 40px;" v-model="addForm.title" placeholder="请输入"></el-input></el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="cancle">取消</el-button>
					<el-button type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
				</span>
			</template>
		</el-dialog>

		<el-dialog class="deleteDialog" :close-on-click-modal="false" :close-on-press-escape="false" v-model="deleteDialog" title="" top="30vh" width="20.5%">
			<img width="50" height="50" src="../../assets/images/mainImg/gth.png" />
			<p v-if="!isInDocument" class="blk">你确定要删除"{{ wjTitle }}"资料夹及其 文件?</p>
			<p v-else class="blk">你确定要删除"{{ wjTitle }}"文件?</p>
			<p class="red">删除操作不可恢复</p>
			<template #footer>
				<span class="dialog-footer" style="text-align: center;">
					<el-button @click="deleteDialog = false">取消</el-button>
					<el-button type="primary" @click="deleteData()">确定</el-button>
				</span>
			</template>
		</el-dialog>
		<el-dialog class="uplodDialog" :close-on-click-modal="false" :close-on-press-escape="false" v-model="uplodDialog" title="" top="30vh" width="20.5%">
			<el-upload
				ref="upload"
				:file-list="myFileList"
				class="upload-demo"
				drag
				:action="action"
				multiple
				:headers="headers"
				:on-preview="handlePreview"
				:on-exceed="handleExceed"
				:before-upload="beforeUpload"
				:on-remove="remove"
				:on-progress="handProgress"
				:on-success="handSuccess"
				:on-change="handChange"
				:show-file-list="true"
			>
				<el-icon class="el-icon--upload"><upload-filled /></el-icon>
				<div class="el-upload__text">
					点击上传文件
					<em>或者拖拽上传</em>
				</div>
			</el-upload>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="qxSc">取消</el-button>
					<el-button type="primary" @click="uploadWj()">保存</el-button>
				</span>
			</template>
		</el-dialog>
		
	</div>
</template>

<script lang="ts" setup>
import { getFolderList, deleteFolder, addFolder, editFolder,fileUploads,addDocument,getDoucument,deleteDocument,download } from '@/api/hkd';
import useUserStore from '@/store/modules/user';
import { ElMessage, ElLoading, FormInstance  } from 'element-plus';
import { UploadFilled } from '@element-plus/icons-vue';
import { getToken } from "@/utils/auth";
import axios from 'axios';
import { resolveSoa } from 'dns';
const ruleFormRef = ref<FormInstance>();
const { proxy } = getCurrentInstance();
const loading = ref(true);
const tableList = ref([]);
const total = ref(0);
const projectId = ref('');
const projectName = ref('');
const addDialog = ref(false);
const deleteDialog = ref(false);
const uplodDialog = ref(false);
const isInDocument = ref(false);
const userName = ref(useUserStore().name);
const deletId = ref('');
const wjTitle = ref('');
const zlName = ref('');
const folderId = ref('');
//上传的
const myFileList= ref([]);
const lbXsFileList= ref([]);
const allfilesList= ref([]);
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const action = import.meta.env.VITE_APP_BASE_API + '/common/upload';
const headers = { 'Authorization': 'Bearer ' + getToken() };
let loadingText = ref(null);
let loding = ref(null);
let showFile = ref(false);

const data = reactive({
	queryParams: {
		pageNum: 1,
		pageSize: 10
	},
	addForm:{
		title:''
	},
	docForm:{
		documentList:[]
	},
	rules: {
		title: [{ required: true, message: '请输入资料夹名称', trigger: 'change' }]
	},
	fileData:new FormData()
});

const { queryParams, addForm, rules, docForm } = toRefs(data);

onMounted(() => {
	if (proxy.$route.query) {
		projectId.value = proxy.$route.query.projectId;
		projectName.value = proxy.$route.query.projectName;
		getList();
	}
});
function comeBack(){
	isInDocument.value = false
	getList()
}
function qkFlie(){
	data.fileData = new FormData();
	myFileList.value = []
	docForm.value.documentList = []
}
function qxSc(){
	uplodDialog.value = false;
	qkFlie()
}
function seeWjk(row){
	isInDocument.value = true
	zlName.value = row.title
	folderId.value = row.id
	getInDocument()

}
function showUpload(item){
	docForm.value.id = item.id
	qkFlie()
	uplodDialog.value = true
}
function handChange(uploadFile, uploadFiles) {
	// debugger
	// console.log("change", uploadFile, uploadFiles);
}
function changeFile(file) {
	 // console.log(file);
	 // lbXsFileList.value.push(file)

}
function handProgress(evt, uploadFile, uploadFiles) {
	//console.log(evt, Number((evt.loaded / evt.total) * 100));
	showFile.value = false;
	loding.value = ElLoading.service({
		lock: true,
		text: '上传中，请稍等......',
		background: 'rgba(0, 0, 0, 0.7)',
	})
}
function handSuccess(uploadFile, uploadFiles, list) {
	loding.value.close();
	showFile.value = true;
	docForm.value.documentList.push({
		documentName: uploadFiles.raw.name,
		documentSize: uploadFiles.raw.size,
		documentType: uploadFiles.raw.type,
		filePath:uploadFile.fileName,
	})

}
function handlePreview(uploadFile) {
	// console.log("preview", uploadFile);

}
// function handProgress(a,b,c,d) {
// 	debugger
// 	console.log(a);
// 	console.log(b);
// 	console.log(c);
// 	console.log(d);

// }
function handleExceed(files, uploadFiles) {
	// console.log("exceed", files, uploadFiles);

}

function beforeUpload(file, fileList, scope) {
	let imgSize = Number(file.size / 1024 / 1024);
	if (imgSize > 200) {
		ElMessage({ message: '文件大小不能超过200MB，请重新上传。', type: 'warning', duration: 1 * 1000 })
		return false;
	}
}
// 移除文件列表
function remove(file, fileList) {
//第二种
	docForm.value.documentList.map((item,index)=>{
		if(file.name==item.documentName){
			docForm.value.documentList.splice(index,1)
		}
	})
}


//新增资料库
function addFolders(){
	addDialog.value = true;

}
function cancle(){
	addDialog.value = false;
	addForm.value.title = ''
}

function deleteWjk(row){
	deleteDialog.value = true
	deletId.value = row.id?row.id:row.documentId
	wjTitle.value = row.title?row.title:row.documentName
}
function deleteData(){
	if(isInDocument.value){
		deleteDocument(deletId.value).then(res=>{
			if(res.code =='200'){
				   ElMessage({ message: '删除成功！', type: 'success', duration: 1 * 1000 })
				   getInDocument()
				   deleteDialog.value = false
			}else{
				ElMessage({ message: res.msg, type: 'error', duration: 1 * 1000 })
			}
		})
	}else{
		deleteFolder(deletId.value).then(res=>{
			if(res.code =='200'){
				   ElMessage({ message: '删除成功！', type: 'success', duration: 1 * 1000 })
				   getList()
				   deleteDialog.value = false
			}else{
				ElMessage({ message: res.msg, type: 'error', duration: 1 * 1000 })
			}
		})
	}

}

function getInDocument(){
	//loading.value = true;
	getDoucument({ documentFolderId: folderId.value }).then(res => {
		if(res.code===200){
			tableList.value = res.data;
			//loading.value = false;
		}
	});
}
function uploadWj(){
	uplodDialog.value = false
	//loading.value  = true
	addDocument(docForm.value).then(res => {
		if (res.code == 200) {
			ElMessage({ message: '上传成功！', type: 'success', duration: 1 * 1000 })
			//loading.value  = false
			docForm.value.documentList = []
			getList()
		}else {
			ElMessage({ message: res.msg, type: 'error', duration: 1 * 1000 })
		}
	});
	// lbXsFileList.value.map(item=>{
	// 	docForm.value.documentList.push({
	// 		documentName: item.file.name,
	// 		documentSize: item.file.size,
	// 		documentType: item.file.type,
	// 		filePath:'',
	// 	})
	// 	data.fileData.append('files', item.file); //传文件
	// })
	// fileUploads(data.fileData).then(res=>{
	// 	if(res.code===200){

	// 		docForm.value.projectId  = projectId.value
	// 		for(let i=0;i<docForm.value.documentList.length;i++){
	// 			docForm.value.documentList[i]['filePath'] = res.fileNames.split(',')[i]
	// 		}

	// 		addDocument(docForm.value).then(res => {
	// 			if (res.code == 200) {
	// 				ElMessage({ message: '上传成功！', type: 'success', duration: 1 * 1000 })
	// 				loading.value  = false
	// 				docForm.value.documentList = []
	// 				getList()
	// 			}else {
	// 				ElMessage({ message: res.msg, type: 'error', duration: 1 * 1000 })
	// 			}

	// 		});
	// 	}else{
	// 		ElMessage({ message: res.msg, type: 'error', duration: 1 * 1000 })
	// 	}

	// })
}


const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
		let form = JSON.parse(JSON.stringify(addForm.value ))
			form.projectId  = projectId.value
			addFolder(form).then(res=>{
				if(res.code =='200'){
					   ElMessage({ message: '新增成功！', type: 'success', duration: 1 * 1000 })
					   getList()
					   addDialog.value = false
				}else{
					ElMessage({ message: res.msg, type: 'error', duration: 1 * 1000 })
				}
			})
    } else {
    }
  })
}
function downloadFile(item) {
	//loading.value = true;
	//loading.value = true;
	loding.value = ElLoading.service({
		lock: true,
		text: '下载中，请稍等......',
		background: 'rgba(0, 0, 0, 0.7)',
	})
	const url = baseUrl + item.filePath;
	fetch(url).then(res => {
		if (res.status == 404) {
			ElMessage({ message: '文件不存在', type: 'error', duration: 1 * 1000 })
		} else {
			const a = document.createElement('a');
			a.style.display = 'none';
			a.href = url;
			// 保存下来的文件名
			a.download = item.documentName;
			document.body.appendChild(a);
			a.click();
			// 移除元素
			document.body.removeChild(a);
		}
		loding.value.close();
	})
}

function getList() {
	loading.value = true;
	queryParams.value.projectId = projectId.value;
	getFolderList(queryParams.value).then(response => {
		tableList.value = response.rows;
		total.value = response.total;
		loading.value = false;
	});
}
</script>

<style lang="scss" scoped>
.qjButtonBox {
	padding: 20px 30px;
}

.dialog-footer button:first-child {
	margin-right: 10px;
}
:deep(.el-form) {
	display: flex;
	.left {
		// height: 100px;
		border-right: 2px dashed #e5e1e1;
	}
}
.userOption {
	display: flex;
	align-items: center;
	width: 1.5rem;
	height: 1.5rem;
	border-radius: 50%;

	img {
		width: 100%;
		height: 100%;
		border-radius: 50%;
	}

	span {
		padding: 0 1rem;
	}
}
.sxm {
	margin-top: 20px;
}
.spBox,
.spBox2 {
	display: flex;
	flex-flow: column;

	p {
		margin-top: 0;
	}
	img {
		width: 45px;
		height: 45px;
		border-radius: 50%;
	}
}
.spBox2 {
	margin-right: 20px;
}
:deep(.left) {
	width: 50%;
	.el-form-item {
		display: flex;
		flex-flow: column;
	}
}
:deep(.right) {
	margin-left: 50px;
	width: 42%;
	.el-form-item {
		display: flex;
		flex-flow: column;
	}
	.spr,
	.csr {
		margin-bottom: 10px;
		.el-form-item__label {
			width: 70px !important;
		}
	}
}
.csrBox {
	margin-top: 20px;
	display: flex;
	max-height: 235px;
	overflow: auto;
	display: flex;
	flex-flow: wrap;
}
.csrBox::-webkit-scrollbar {
	display: none; /* Chrome Safari */
}

.ztbox {
	display: flex;
	align-items: center;
	justify-content: center;
	.dian {
		margin-right: 8px;
		width: 7px;
		height: 7px;
		border-radius: 50%;
	}
}
.czan {
	display: flex;
	justify-content: center;
}
#printDivdyAll {
	margin-top: -23px;
	width: 1000px;
	height: 400px;
	padding: 5px;

	td {
		text-align: center;
		font-size: 18px;
	}

	.zhai {
		height: 60px;
	}

	.shense {
		font-size: 20px;
	}

	table {
		width: 100%;
		height: 100%;
	}
}
.zBox{
	height: 99.8%;
	background-color: #ffffff;
	border-radius: 10px;
	padding: 20px;
}

.sptop {
	margin-top: 20px;
}
:deep(.bz) {
	.el-form-item__label {
		width: 50px !important;
	}
}
.red {
	color: #ff0000;
}
.spzt {
	width: 20px;
	height: 20px;
	display: inline-block;
	background-size: contain;
	margin-right: 10px;
}
.jdbox {
	position: relative;
}
.jdbox:last-child .xuLine {
	display: none;
}
.xuLine {
	position: absolute;
	width: 1px;
	height: 17px;
	border-left: 2px dashed rgb(204, 204, 204);
	left: 9px;
	top: 20px;
}
:deep(.qjTable) {
	.el-table__header-wrapper,
	.el-table__fixed-header-wrapper {
		th {
			word-break: break-word;
			background-color: #f7f7f7 !important;
			color: #515a6e;
			height: 58px !important;
			font-size: 13px;
			border: none !important;
		}
	}
	.el-table__body-wrapper {
		.el-button [class*='el-icon-'] + span {
			margin-left: 1px;
		}
		.el-table__row {
			td {
				border: none !important;
				height: 54px;
			}
		}
	}
}
.title {
	font-size: 16px;
	font-weight: 600;
	margin-bottom: 20px;
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.qjBut {
	background: #be1a21;
	color: #ffffff;

	text-align: center;
	border-radius: 4px;
	padding: 10px;
	font-size: 0.875rem;
	cursor: pointer;
	span {
		margin: 0 !important;
		font-weight: 400;
	}
}
.hbj {
	background: #eeeeeeff;
	color: #999999ff;
	text-align: center;
	border-radius: 4px;
	padding: 10px;
	font-size: 0.875rem;
	cursor: pointer;
	span {
		margin: 0 !important;
		font-weight: 400;
	}
}
.qjBut::before {
	content: '';
	padding-left: 20px;
	background: url(../../assets/images/mainImg/add.png) no-repeat;
	background-size: 90%;
}

:deep(.deleteDialog) {
	.el-dialog__body {
		text-align: center;
	}
	.blk {
		font-weight: 600;
		color: #000;
	}
}
:deep(.upload-demo) {
	.el-upload-dragger {
		background-color: #fafafa;
		padding: 70px 20px;
	}
	.el-upload-dragger .el-icon--upload {
		color: #be1a21ff;
	}
	.el-upload-dragger .el-upload__text {
		color: #be1a21ff;
	}
	.el-upload-dragger .el-upload__text em {
		color: #606266;
	}
	.el-upload-list__item-name {
		padding: 5px 4px;
	}
}
</style>
